package com.example.demo.controller;

import com.example.demo.dto.OrderStatisticsDTO;
import com.example.demo.dto.ResponseResult;
import com.example.demo.entity.Order;
import com.example.demo.service.OrderService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("app/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    @PostMapping("/create")
    public ResponseResult<Order> createOrder(@RequestParam int userId, @RequestParam int serviceId,
                                             @RequestParam double amount) {
        try{
            Order order = orderService.createOrder(userId, serviceId, amount);
            return new ResponseResult<>(200,"订单创建成功",order);
        }catch (Exception e){
            return new ResponseResult<>(500,"订单创建失败：" + e.getMessage(),null);
        }

    }

    @PutMapping("/{id}/status")
    public ResponseResult<Object> updateOrderStatus(@PathVariable int id, @RequestParam int status) {
        boolean success = orderService.updateOrderStatus(id, status);
        if (success) {
            return new ResponseResult<>(200,"更新状态成功",null);
        } else {
            return new ResponseResult<>(500,"更新状态失败",null);
        }
    }
    // 订单退款接口
    @PostMapping("/refund")
    public ResponseResult<Object> refundOrder(
            @RequestParam String orderNo) {
        try {
            boolean success = orderService.refundOrder(orderNo);
            if (success) {
                return new ResponseResult<>(200, "退款申请成功");
            } else {
                return new ResponseResult<>(500, "退款申请失败");
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "退款异常：" + e.getMessage());
        }
    }
    // 订单统计接口
    @GetMapping("/get/statistics")
    public ResponseResult<OrderStatisticsDTO> getOrderStatistics(
            @RequestParam int userId) {
        if(userService.getUserById(userId) == null) {
            return new ResponseResult<>(400,"用户不存在");
        }
        try {
            OrderStatisticsDTO stats = orderService.getOrderStatistics(userId);
            return new ResponseResult<>(200, "获取订单统计信息成功", stats);
        } catch (Exception e){
            return new ResponseResult<>(500,"获取订单统计信息失败：" + e.getMessage());
        }
    }

    // 订单列表接口
    @GetMapping("/get/list")
    public ResponseResult<List<Order>> getOrderList(
            @RequestParam int userId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Double minAmount,
            @RequestParam(required = false) Double maxAmount,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        if(userService.getUserById(userId) == null) {
            return new ResponseResult<>(400,"获取订单信息失败");
        }
        try {
            List<Order> orders = orderService.getOrderList(userId, status, minAmount, maxAmount, startTime, endTime, pageNum, pageSize);
            return new ResponseResult<>(200, "获取订单列表信息成功", orders);
        }catch (Exception e){
            return new ResponseResult<>(500,"获取订单信息失败：" + e.getMessage());
        }
    }

    //获取分类订单数据
    @GetMapping("/get/orders")
    public ResponseResult<List<Order>> getOrders(
            @RequestParam int userId,
            @RequestParam Integer status,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize
    ){
        if(userService.getUserById(userId) == null) {
            return new ResponseResult<>(400,"获取订单信息失败");
        }
        try {
            List<Order> orders = orderService.getOrders(userId, status, pageNum, pageSize);
            return new ResponseResult<>(200, "获取订单列表信息成功", orders);
        }catch (Exception e){
            return new ResponseResult<>(500,"获取订单信息失败：" + e.getMessage());
        }
    }

    //获取全部订单数据
    @GetMapping("/get/allorders")
    public ResponseResult<List<Order>> getAllOrders(
            @RequestParam int userId
    ){
        if(userService.getUserById(userId) == null) {
            return new ResponseResult<>(400,"获取订单信息失败");
        }
        try {
            List<Order> orders = orderService.getAllOrders(userId);
            return new ResponseResult<>(200, "获取订单列表信息成功", orders);
        }catch (Exception e){
            return new ResponseResult<>(500,"获取订单信息失败：" + e.getMessage());
        }
    }

    @GetMapping("/get/search")
    public ResponseResult<List<Order>> searchOrdersByServiceName(
            @RequestParam int userId,
            @RequestParam String serviceName) {
        if (userService.getUserById(userId) == null) {
            return new ResponseResult<>(400, "用户不存在");
        }
        try {
            List<Order> orders = orderService.searchOrdersByServiceName(userId, serviceName);
            return new ResponseResult<>(200, "搜索订单成功", orders);
        } catch (Exception e) {
            return new ResponseResult<>(500, "搜索订单失败：" + e.getMessage());
        }
    }

    // 订单详情接口
    @GetMapping("/get/detail/{orderId}")
    public ResponseResult<Order> getOrderDetail(@PathVariable int orderId) {
        try {
            Order order = orderService.getOrderById(orderId);
            if (order != null) {
                return new ResponseResult<>(200, "success", order);
            } else {
                return new ResponseResult<>(400, "订单不存在");
            }
        }catch (Exception e){
            return new ResponseResult<>(500,"获取订单详情失败：" + e.getMessage());
        }


    }
    
    // 订单状态查询接口（用于支付轮询）
    @GetMapping("/status")
    public ResponseResult<Map<String, Object>> getOrderStatus(@RequestParam String orderNo) {
        try {
            Order order = orderService.getOrder(orderNo);
            if (order == null) {
                return new ResponseResult<>(400, "订单不存在", null);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("orderNo", orderNo);
            result.put("status", order.getStatus());
            result.put("amount", order.getAmount());
            
            // 根据状态返回不同的状态标识
            if (order.getStatus() == 1) { // 假设1表示已支付
                result.put("status", "PAID");
            } else if (order.getStatus() == 2) { // 假设2表示支付失败
                result.put("status", "FAILED");
            } else {
                result.put("status", "PENDING");
            }
            
            return new ResponseResult<>(200, "success", result);
        } catch (Exception e) {
            return new ResponseResult<>(500, "查询订单状态失败：" + e.getMessage(), null);
        }
    }
    
}
